 %%% this code plots the country graphs created by make_country_graphs.m

%clear
%clo  se all
%clc
    
set(0,'DefaultFigureWindowStyle','normal','DefaultFigureVisible','on') % I stopped doing the docked thing because it doesn't allow to specify size and gives inconsistent results across computers

addpath('../../Toolbox/export_fig/');
addpath('../../Toolbox/struct2csv/');

graph_width=800;
graph_height=600;

% -----------------------
% DEFINE FOLDER LOCATIONS

folders;

% save?s
save_graphs=1;

% what to plot?
basic = 0;
pop_map = 0;
actual = 1;
grid = 1;
rugged_map=0;
path_save_grid_plots = path_papers_graph;
WP=0;
osm=0;

%% load country list
country_list_short;

%% set discretization parameters to load the data
 % x_diag = 0;      % same, for diagonal paths
default_cellsize = 0.5;

% keep largest connected?
largest_connected = 1;

%% generate figure for Spain and France
for country_n = 1:Ncountries
% country_n=1;

    %% load map
    country_icc = char( countries(country_n) );  % country ICC code
    
    country = icc2name( country_icc );
    
    % Set tolerance depending on country
    x_ver_hor = get_threshold(country);
    x_diag = x_ver_hor;
    x_thresh =  x_ver_hor;
    
    disp( ['Country: ',country] )
    
    % list of links to exclude
    exclude = get_exclusion(country);
    
    % load in the full grid mat 
    load( [ path_load_grids,country, '_grid_',...
        num2str( x_diag ),'_',...
        num2str( x_ver_hor ),'_',...
        num2str( default_cellsize ),'_connected', ...
        num2str( largest_connected ), ...
        '_WP', num2str(WP), '_osm', num2str(osm),'_test.mat' ]  );
    
    if actual == 1
        load( [ path_load_grids,country,'_roads.mat'] )
        roads = roads_export;
        
        road_use_mat = cell2mat( {roads.use} )';
        road_lanes_mat = cell2mat( {roads.lanes} )';
    end

    % unpack
    places_grid=country_graph.places_grid;
    gridmap=country_graph.gridmap;
    places2=country_graph.places2;
    discretized_roads=country_graph.discretized_roads;
    graph_export=country_graph.graph_export;
    unique_edges=country_graph.unique_edges;
    edges = country_graph.edges;
    unique_nodes=country_graph.unique_nodes;
    dist_info = country_graph.dist_info;
    
    % country bounds
    country_bounds=country_graph.country_bounds;
    
    %% compute some variables used in figures
    
    discretized_avI = cell2mat( {discretized_roads.avI} )';
    discretized_use = cell2mat( {discretized_roads.use} )';
    discretized_lanes = cell2mat( {discretized_roads.lanes} )';
    
    max_disc_avI = max( discretized_avI );
    
    keep_discretized = cell2mat( {discretized_roads.keep} )';  % these are the links that are kept
    
    %tabulate(discretized_avI)
    discretized_avI_int = round( discretized_avI );
    discretized_avI_int( ~keep_discretized ) = 0.1;
    %tabulate(discretized_avI_int)
    
    % common parameters to all graphs
    bright_line = 0.5;  % higher=brighter
    bright_nodes = 0.4; % higher=brighter
    max_bright = 5;    % higher=darker lines
    adj_width = 0.3;
    markersize = 5;
    color_growth = [ 0 1 0 ];   % red = [ 1 0 0 ]  green = [ 0 1 0 ] blue = [ 0 0 1 ]
    color_shrink = [ 1 0 0 ];
    
    % number of categories for plotting
    N_cat = numel( unique( cell2mat( {gridmap.quantiles} ) ) )-1;

    
        %% population
        close(figure(1))
        fig=figure(1);
        %set(fig,'Position',[0 0 graph_width graph_height])_large;
        
        mapshow( country_bounds,'FaceColor','Black');
        
        % population
        for i=N_cat+1:-1:1
            relsize = bright_nodes+(1-bright_nodes)*i/( N_cat+1 );
            mapshow( gridmap( cell2mat( {gridmap.quantiles} )==i ),...
                'FaceColor',relsize*[ 0 1 1 ] )
        end
        
        
         mapshow( gridmap( cell2mat( {gridmap.quantiles} )==0 ),...
            'FaceColor',[ 1 1 1 ] )
     
        
        % centroids
        for i=N_cat+1:-1:1
            
            relsize = bright_nodes+(1-bright_nodes)*i/( N_cat+1 );
            
            mapshow( places2( cell2mat( {gridmap.quantiles} )==i ),...
                'Marker','o',...
                'MarkerFaceColor',relsize*[ 0 1 1 ],...
                'MarkerEdgeColor',[ 0 0 0 ],...
                'MarkerSize',6 )
        end
        
        margin = 0.5;
        Xlim = [ min( cell2mat({country_bounds.X}) )-margin;max( cell2mat({country_bounds.X}) )+margin ];
        Ylim = [ min( cell2mat({country_bounds.Y}) )-margin;max( cell2mat({country_bounds.Y}) )+margin ];
        set( gca,'XTick',[],'YTick',[],'XLim',Xlim,'YLim',Ylim,'Box','on' )
        
        if save_graphs
            %             print([ path_papers_graph,country,...
            %                         '_pop.pdf' ],'-dpdf','-fillpage')
            export_fig([ path_papers_graph,country,'_pop.eps' ], '-depsc');
        end
        
        % income
        close(figure(2))
        h=figure(2);
            
        mapshow( country_bounds,'FaceColor','Black');
        
        % income
        for i=N_cat+1:-1:1
            relsize = bright_nodes+(1-bright_nodes)*i/( N_cat+1 );
            mapshow( gridmap( cell2mat( {gridmap.quantiles_inc} )==i ),...
                'FaceColor',relsize*[ 0 1 1 ] )
            
        end
            mapshow( gridmap( cell2mat( {gridmap.quantiles_inc} )==0 ),...
                'FaceColor',[ 1 1 1 ] )
       
        % centroids
        for i=N_cat+1:-1:1

            relsize = bright_nodes+(1-bright_nodes)*i/( N_cat+1 );
            mapshow( places2( cell2mat( {gridmap.quantiles_inc} )==i ),...
                    'Marker','o',...
                    'MarkerFaceColor',relsize*[ 0 1 1 ],...
                    'MarkerEdgeColor',[ 0 0 0 ],...
                    'MarkerSize',markersize )

        end

            margin = 0.5;
            Xlim = [ min( cell2mat({country_bounds.X}) )-margin;max( cell2mat({country_bounds.X}) )+margin ];
            Ylim = [ min( cell2mat({country_bounds.Y}) )-margin;max( cell2mat({country_bounds.Y}) )+margin ];
            set( gca,'XTick',[],'YTick',[],'XLim',Xlim,'YLim',Ylim,'Box','on' )


        if save_graphs

            export_fig([path_save_grid_plots,country,'_income.eps' ], '-depsc');

        end
 
     
        %% baseline grid
        close(figure(3))
        h=figure(3);
        set(h,'Position',[0 0 graph_width graph_height]);

        mapshow( country_bounds,'FaceColor','Black');

        mapshow( gridmap,...
            'FaceColor','Black',...
            'EdgeColor','White','LineWidth', 0.5 )
       
       
        mapshow( discretized_roads,...
            'Color',[ 1 0 0 ],...
            'LineWidth', 1  )

        for i=N_cat+1:-1:1

            relsize = bright_nodes+(1-bright_nodes)*i/( N_cat+1 );

            mapshow( places2( cell2mat( {gridmap.quantiles} )==i ),...
                'Marker','o',...
                'MarkerFaceColor',relsize*[ 0 1 1 ],...
                'MarkerEdgeColor',[ 0 0 0 ],...
                'MarkerSize',markersize )
        end


        margin = 0.5;
        Xlim = [ min( cell2mat({country_bounds.X}) )-margin;max( cell2mat({country_bounds.X}) )+margin ];
        Ylim = [ min( cell2mat({country_bounds.Y}) )-margin;max( cell2mat({country_bounds.Y}) )+margin ];
        set( gca,'XTick',[],'YTick',[],'XLim',Xlim,'YLim',Ylim,'Box','on' )
        
        if save_graphs
            export_fig([ path_papers_graph,country,'_baseline_grid.png' ]);
        end
   
   
      %% actual centroids and actual (non-discretized) infrastructure
      if actual == 1

        close(figure(4))
        h=figure(4);
        set(h,'Position',[0 0 graph_width graph_height]);
        
        % show bounds
        mapshow( country_bounds,...
            'FaceColor','Black',...
            'EdgeColor','White','LineWidth', 0.5 )
            
        % show bounds
        mapshow( roads,...
            'Color','Red','LineWidth', 1 )

      
        % show roads
        lanes_list = unique(road_lanes_mat);
        for k=1:length(lanes_list)
            j = lanes_list(k);
           
            keep = logical( ( road_lanes_mat==j ).*( road_use_mat==0 ) );
            mapshow( roads( keep ),...
                'Color',min( bright_line+( 1-bright_line )*(1.3*j)/max_bright*[ 1 0 0 ],1 ),...
                'LineWidth', j*adj_width*0.5  );
            
            keep = logical( ( road_lanes_mat==j ).*( road_use_mat==1 ) );
            mapshow( roads( keep ),...
                'Color',min( bright_line+( 1-bright_line )*(4*j)/max_bright*[ 0 1 0 ],1 ),...
                'LineWidth', j*adj_width*1.3  );
            
        end
        
            
        % centroids
        for i=N_cat+1:-1:1
            
            relsize = bright_nodes+(1-bright_nodes)*i/( N_cat+1 );
            
            mapshow( places2( cell2mat( {gridmap.quantiles} )==i ),...
                'Marker','o',...
                'MarkerFaceColor',relsize*[ 0 1 1 ],...
                'MarkerEdgeColor',[ 0 0 0 ],...
                'MarkerSize',markersize )
        end
        
        margin = 0.5;
        Xlim = [ min( cell2mat({country_bounds.X}) )-margin;max( cell2mat({country_bounds.X}) )+margin ];
        Ylim = [ min( cell2mat({country_bounds.Y}) )-margin;max( cell2mat({country_bounds.Y}) )+margin ];
        set( gca,'XTick',[],'YTick',[],'XLim',Xlim,'YLim',Ylim,'Box','on' )
        
        if save_graphs
            %             print([ path_papers_graph,country,...
            %                         '_actual_network.pdf' ],'-dpdf','-fillpage')
            %             saveas(h,[ path_papers_graph,country,...
            %                             '_actual_network.png' ])
            
            export_fig([ path_papers_graph,country,'_actual_network.eps' ], '-depsc');
            export_fig([ path_papers_graph,country,'_actual_network.png' ]);
        end  
 
      end
        
      %% actual centroids and actual (discretized) infrastructure
        close(figure(5))
        h=figure(5);
        set(h,'Position',[0 0 graph_width graph_height]);
        
        % bounds
        mapshow( country_bounds,...
            'FaceColor','Black',...
            'EdgeColor','White','LineWidth', 0.5 )
        
        % show lanes and use
        for j=1:length( discretized_roads )
       
            if discretized_roads(j).avI>1e-4 

                colorweight = discretized_lanes(j)/max_bright;
                
                color =  bright_line + ( 1-bright_line ) * colorweight * ...
                    ( discretized_use(j)*[ 0 1 0 ] +...
                    + ( 1-discretized_use(j) )*[ 1 0 0 ] );
                
                mapshow( discretized_roads( j ),...
                    'Color',min( color,1 ),...
                    'LineWidth',discretized_lanes(j)*adj_width*2.5 )

            end
        end
        
        for i=N_cat+1:-1:1
            
            relsize = bright_nodes+(1-bright_nodes)*i/( N_cat+1 );
            
            mapshow( places2( cell2mat( {gridmap.quantiles} )==i ),...
                'Marker','o',...
                'MarkerFaceColor',relsize*[ 0 1 1 ],...
                'MarkerEdgeColor',[ 0 0 0 ],...
                'MarkerSize',markersize )
        end
        
        margin = 0.5;
        Xlim = [ min( cell2mat({country_bounds.X}) )-margin;max( cell2mat({country_bounds.X}) )+margin ];
        Ylim = [ min( cell2mat({country_bounds.Y}) )-margin;max( cell2mat({country_bounds.Y}) )+margin ];
        set( gca,'XTick',[],'YTick',[],'XLim',Xlim,'YLim',Ylim,'Box','on' )
        if save_graphs
            export_fig([ path_papers_graph,country,'_connected', ...
                num2str(largest_connected), '_tol', num2str(x_thresh),  '_discrete_network.png' ], '-transparent');
        end 
end
